package org.example.ams.service.impl.system;

import org.example.ams.dao.system.ISysUserDao;
import org.example.ams.entity.system.SecurityUser;
import org.example.ams.entity.system.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserDao.selectUserWithPermissionByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 判断是否是超级管理员
        if (sysUser.getIsAdmin()) {
            // 设置拥有所有的权限
            HashSet<String> permissions = new HashSet<>();
            permissions.add("*:*:*");
            sysUser.setPermissions(permissions);
        }
        return new SecurityUser(sysUser);
    }
}
